package edu.kit.aifb.ldstream.learner.query;

import org.openrdf.model.URI;
import org.semanticweb.yars.nx.namespace.RDF;
import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;

import edu.kit.aifb.ldstream.env.Environment;


class InstanceQuery {

	private RepositoryConnection con;
	private TupleQueryResult result;
	private String type;

	InstanceQuery(URI type){
		this.type = " <" + type.stringValue() + "> ";
		try {
			this.con = Environment.REPO.getConnection();
		} catch (RepositoryException e) {
			e.printStackTrace();
		}
		init();
	}

	private void init(){
		/*
		String query = "SELECT DISTINCT ?instance FROM <" + Environment.STREAM_CONTEXT_URI.stringValue() + "> "
				+ " WHERE{ ?instance " + RDF.TYPE.toN3() + this.type +" FILTER( ! isBLANK(?instance) ) }";
		 */
		String query = "SELECT DISTINCT ?instance  WHERE{ ?instance " + RDF.TYPE.toN3() + " " + this.type +" FILTER( !isBLANK(?instance) ) }";
		try {
			TupleQuery tupleQuery = this.con.prepareTupleQuery(QueryLanguage.SPARQL, query);
			this.result = tupleQuery.evaluate();
		} catch (RepositoryException e) {
			e.printStackTrace();
		} catch (MalformedQueryException e) {
			e.printStackTrace();
		} catch (QueryEvaluationException e) {
			e.printStackTrace();
		}
	}

	boolean hasNext(){
		boolean hasNext = false;
		try {
			hasNext = this.result.hasNext();
		} catch (QueryEvaluationException e) {
			e.printStackTrace();
		}
		return hasNext;
	}

	URI next(){
		URI next = null;
		try {
			if(hasNext()){
				next = (URI) this.result.next().getValue("instance");
			}
		} catch (QueryEvaluationException e) {
			e.printStackTrace();
		}
		return next;
	}

	void close(){
		try {
			this.result.close();
		} catch (QueryEvaluationException e) {
			e.printStackTrace();
		}
		try {
			this.con.close();
		} catch (RepositoryException e) {
			e.printStackTrace();
		}
	}


}
